<template>
  <div class="profile-container">
    <div class="section-title">个人信息</div>
    
    <el-form :model="profileForm" label-width="100px" size="small" class="profile-form">
      <el-form-item class="avatar-item" label-width="0">
        <div class="avatar-uploader" @click="openAvatarDialog">
          <img 
            :src="profileForm.userPic || defaultAvatar" 
            class="avatar-image"
            @error="handleAvatarError"
            @load="handleAvatarLoad"
          />
          <div class="upload-overlay">
            <el-icon><Upload /></el-icon>
            <span>更换头像</span>
          </div>
        </div>
      </el-form-item>
      
      <el-form-item label="用户名：">
        <el-input v-model="profileForm.username" placeholder="请输入用户名" />
      </el-form-item>
      
      
      <el-form-item label="性别：">
        <el-radio-group v-model="profileForm.sex">
          <el-radio :label="1">男</el-radio>
          <el-radio :label="2">女</el-radio>
          <el-radio :label="0">保密</el-radio>
        </el-radio-group>
      </el-form-item>
      
    
      
      <el-form-item label="电子邮箱：">
        <div class="readonly-text">{{ profileForm.email || '-' }}</div>
      </el-form-item>
    

      <el-form-item label="账户余额：">
        <div class="balance-wrap">
          <span class="currency">¥</span>
          <span class="amount">{{ Number(profileForm.balance).toFixed(2) }}</span>
          <div class="balance-actions">
            <el-button type="primary" size="small" @click="openRechargeDialog">余额充值</el-button>
            <el-button type="primary" size="small" @click="openOrderListDialog">查询充值订单</el-button>
          </div>
        </div>
      </el-form-item>

      <el-form-item label="账号状态：">
        <el-tag :type="profileForm.status === '正常' ? 'success' : (profileForm.status === '冻结' ? 'warning' : '')">
          {{ profileForm.status || '未知' }}
        </el-tag>
      </el-form-item>
      
      <el-form-item label-width="0" class="actions">
        <el-button type="primary" class="save-btn" @click="saveProfile">保存修改</el-button>
      </el-form-item>
    </el-form>
    <!-- 更换头像弹窗 -->
    <el-dialog v-model="avatarDialogVisible" title="更换头像" width="22rem" append-to-body>
      <div class="avatar-dialog">
        <div class="preview">
          <img :src="previewUrl || profileForm.userPic || defaultAvatar" alt="预览" />
        </div>
        <div class="actions-row">
          <input ref="fileInput" type="file" accept="image/*" @change="onFileChange" style="display:none" />
          <el-button @click="triggerFileSelect">选择图片</el-button>
          <el-button type="primary" @click="onUploadConfirm" :disabled="!selectedFile">确定上传</el-button>
          <el-button type="danger" @click="onDeleteAvatar" :disabled="!profileForm.userPic">删除头像</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 余额充值弹窗 -->
    <el-dialog v-model="rechargeDialogVisible" title="余额充值" width="25rem" append-to-body>
      <div class="recharge-dialog">
        <el-form :model="rechargeForm" label-width="80px">
          <el-form-item label="充值金额：">
            <el-input 
              v-model="rechargeForm.amount" 
              type="number" 
              placeholder="请输入充值金额"
              :min="0.01"
              :step="0.01"
            >
              <template #prepend>¥</template>
            </el-input>
          </el-form-item>
        </el-form>
        <div class="dialog-actions">
          <el-button @click="rechargeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmRecharge" :disabled="!rechargeForm.amount || Number(rechargeForm.amount) <= 0">
            确认充值
          </el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 充值订单查询弹窗 -->
    <el-dialog 
      v-model="orderListDialogVisible" 
      title="充值订单查询" 
      width="60rem" 
      height="30rem" 
      append-to-body
      :center="true"
      :lock-scroll="true"
      :close-on-click-modal="false"
      :close-on-press-escape="true"
      :modal="true"
      :show-close="true"
      :draggable="false"
      custom-class="order-dialog-center"
    >
      <div class="order-list-dialog">
        <div class="order-list-header">
          <el-button type="primary" @click="refreshOrderList">刷新订单</el-button>
        </div>
        <el-table 
          :data="orderList" 
          class="order-list-table"
          :empty-text="emptyText"
        >
          <el-table-column prop="orderNo" label="订单号" width="200">
            <template #default="scope">
              <span class="order-no-text">{{ scope.row.orderNo}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="requestAmount" label="充值金额" width="120">
            <template #default="scope">
              <span class="amount-text">¥{{ Number(scope.row.requestAmount).toFixed(2) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.status === 1 ? 'success' : 'warning'">
                {{ scope.row.status === 1 ? '已支付' : (scope.row.status === 2 ? '已退款' : '未支付') }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createdTime" label="创建时间" width="180">
            <template #default="scope">
              {{ scope.row.createdTime || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="completedTime" label="完成时间" width="180">
            <template #default="scope">
              {{ scope.row.completedTime || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" fixed="right" >
            <template #default="scope">
              <el-button 
                v-if="scope.row.status === 0" 
                type="primary" 
                size="small" 
                @click="payOrder(scope.row.orderNo)"
              >
                去支付
              </el-button>
              <el-button 
                v-if="scope.row.status === 1" 
                type="success" 
                size="small" 
                disabled  
              >
                已支付
              </el-button>
              <el-button 
                v-if="scope.row.status === 2" 
                type="warning" 
                size="small"
                disabled         
              >
                已退款
              </el-button>
              <el-button 
                type="danger" 
                size="small" 
                @click="deleteOrder(scope.row.orderNo)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { Upload } from '@element-plus/icons-vue'
import { getUserInfoService, updateUserProfileService, uploadAvatarService, updateAvatarService, deleteAvatarService } from '../../api/user'
import { useUserStore } from '../../stores/user'
import { addChargeOrderService, getChargeOrderListService, deleteChargeOrderService } from '../../api/chargeOrder';
import { AlipayChargePayService } from '../../api/alipay';

const userStore = useUserStore()
// 默认头像（与顶部导航保持一致）
const defaultAvatar = 'https://img.alicdn.com/imgextra/i3/O1CN01IEyHyC1wZL0KJYXlN_!!6000000006324-0-tps-200-200.jpg'

// 头像加载错误处理
const handleAvatarError = (event: Event) => {
  const img = event.target as HTMLImageElement
  console.warn('头像加载失败，使用默认头像:', img.src)
  // 如果当前不是默认头像，则切换到默认头像
  if (img.src !== defaultAvatar) {
    img.src = defaultAvatar
  }
}

// 头像加载成功处理
const handleAvatarLoad = (event: Event) => {
  const img = event.target as HTMLImageElement
  console.log('头像加载成功:', img.src)
}


// 无需使用全局store，这里直接从接口拉取

// 个人资料表单
const profileForm = ref({
  userPic: '',
  username: '',
  sex: 0,
  email: '',
  balance: 0,
  status: ''
})

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const { data } = await getUserInfoService()
    // 依据后端字段名进行适配
    const userPic = data?.userPic || ''
    profileForm.value.userPic = userPic
    userStore.setAvatar(userPic)
    profileForm.value.username = data?.username || ''
    // 同步用户名到顶部导航
    userStore.setUsername(profileForm.value.username)
    profileForm.value.sex = typeof data?.sex === 'number' ? data.sex : 0
    profileForm.value.email = data?.email || ''
    profileForm.value.balance = Number(data?.balance || 0)
    profileForm.value.status = data?.status === 1 ? '正常' : (data?.status === 2 ? '冻结' : '未知')
  } catch (e) {
    console.error('获取用户信息失败:', e)
  }
}

onMounted(fetchUserInfo)

// 保存个人资料（仅用户名、性别）
const saveProfile = async () => {
  try {
  const result=await updateUserProfileService({
      username: profileForm.value.username,
      sex: profileForm.value.sex
    })
    if((result as any)?.code===0){
      ElMessage.success('个人资料保存成功')
      // 保存成功后同步用户名，更新顶部导航
      userStore.setUsername(profileForm.value.username)
    }else{
      ElMessage.error('保存失败，请稍后重试')
    }
  } catch (e) {
    console.error(e)
    ElMessage.error('保存失败，请稍后重试')
  }
}

// 头像弹窗逻辑与上传
const avatarDialogVisible = ref(false)
const selectedFile = ref<File | null>(null)
const previewUrl = ref('')
const fileInput = ref<HTMLInputElement | null>(null)

// 充值相关变量
const rechargeDialogVisible = ref(false)
const rechargeForm = ref({
  amount: ''
})

interface ChargeOrderVo {
  orderNo: string;
  requestAmount: number;
  status: number;
  createdTime: string;
  completedTime: string;
}

// 订单查询相关变量
const orderListDialogVisible = ref(false)
const orderList = ref<ChargeOrderVo[]>([])
const emptyText = ref('您暂时还没有订单记录')

const openAvatarDialog = () => {
  avatarDialogVisible.value = true
  previewUrl.value = profileForm.value.userPic
}

const onFileChange = (e: Event) => {
  const input = e.target as HTMLInputElement
  const f = input.files?.[0]
  if (!f) return
  selectedFile.value = f
  previewUrl.value = URL.createObjectURL(f)
}

const triggerFileSelect = () => fileInput.value?.click()

const onUploadConfirm = async () => {
  if (!selectedFile.value) return
  try {
    // 直接上传所选文件
    const uploadRes = (await uploadAvatarService(selectedFile.value)) as any
    console.log('上传响应:', uploadRes)
   
    const url= uploadRes.data
      
    if (!url) {
      ElMessage.error('上传成功但未返回图片地址')
      return
    }
    console.log('url:'+url);
    
    const result = await updateAvatarService(url)
    if ((result as any)?.code === 0 || (result as any)?.success) {
      profileForm.value.userPic = url
      userStore.setAvatar(url)
      
      avatarDialogVisible.value = false
      // 清理选择状态
      selectedFile.value = null
      previewUrl.value = ''
      ElMessage.success('头像更新成功')
    } else {
      ElMessage.error('更新头像失败')
    }
  } catch (err) {
    console.error(err)
    ElMessage.error('头像上传失败')
  }
}

// 删除头像
const onDeleteAvatar = async () => {
  try {
    const url = profileForm.value.userPic
    const delRes = await deleteAvatarService(url)
    // 即便仅删除了文件，也同步清空用户头像字段
    const updRes = await updateAvatarService('')
    if (((delRes as any)?.code === 0 || (delRes as any)?.success) && ((updRes as any)?.code === 0 || (updRes as any)?.success)) {
      profileForm.value.userPic = ''
      userStore.setAvatar('')
      selectedFile.value = null
      previewUrl.value = ''
      ElMessage.success('头像已删除')
    } else {
      // 兜底：本地也清空，避免界面不同步
      profileForm.value.userPic = ''
      userStore.setAvatar('')
      ElMessage.success('头像已删除')
    }
  } catch (err) {
    console.error(err)
    ElMessage.error('删除头像失败')
  }
}

// 充值相关方法
const openRechargeDialog = () => {
  rechargeDialogVisible.value = true
  rechargeForm.value.amount = ''
}

const confirmRecharge = async () => {
  try {
    const amount = Number(rechargeForm.value.amount)
    if (isNaN(amount) || amount <= 0) {
      ElMessage.error('请输入有效的充值金额')
      return
    }

    // 创建充值订单
    const result = await addChargeOrderService(amount)
    if ((result as any)?.code === 0) {
      const orderNo = (result as any)?.data?.orderNo
      if (orderNo) {
        try {
          payOrder(orderNo);
        } catch (payError: any) {
          console.error('支付页面加载失败:', payError)
          ElMessage.error(`支付页面加载失败: ${payError.message}`)
        }
      } else {
        ElMessage.error('创建订单失败，未获取到订单号')
      }
    } else {
      ElMessage.error('创建充值订单失败')
    }
  } catch (error) {
    ElMessage.error('充值失败，请稍后重试')
  }
}

// 订单查询相关方法
const openOrderListDialog = async () => {
  orderListDialogVisible.value = true
  await refreshOrderList();
}

const refreshOrderList = async () => {
  try {
    const result = await getChargeOrderListService();
    console.log('====================')
    console.log(result);
    console.log('====================')
    if ((result as any)?.code === 0) {
      orderList.value = (result as any)?.data || []
    } else {
      orderList.value = []
      ElMessage.error('获取订单列表失败')
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    orderList.value = []
    ElMessage.error('获取订单列表失败')
  }
}

const payOrder = async (orderNo: string) => {
  try {
          const payResult = await AlipayChargePayService(orderNo)
          const payHtml = payResult.data || payResult

          const tempDiv = document.createElement('div')
          tempDiv.innerHTML = payHtml
          tempDiv.style.display = 'none'
          document.body.appendChild(tempDiv)
          
          // 自动提交表单
          const form = tempDiv.querySelector('form')
          if (form) {
            rechargeDialogVisible.value = false
            ElMessage.success('正在跳转支付宝支付页面...')
            form.submit()
          } else {
            ElMessage.error('支付页面加载失败：未找到支付表单')
          }
          setTimeout(() => {
            if (document.body.contains(tempDiv)) {
              document.body.removeChild(tempDiv)
            }
          }, 1000)
  } catch (payError: any) {
    console.error('支付页面加载失败:', payError)
    ElMessage.error(`支付页面加载失败: ${payError.message}`)
  }
}

const deleteOrder = async (orderNo: string) => {
  try {
    const result = await deleteChargeOrderService(orderNo)
    console.log('删除订单结果:', result)
    if ((result as any)?.code === 0) {
      ElMessage.success('订单删除成功')
      await refreshOrderList();
    } else {
      ElMessage.error('订单删除失败')
    }
  } catch (error) {
    console.error('删除订单失败:', error)
    ElMessage.error('删除订单失败')
  }
}
</script>

<style scoped lang="scss">
.profile-container {
  padding: 0.5rem 0.5rem 0.25rem;
  min-height: 6rem; /* 仅个人资料页控制自身最小高度 */
}

.section-title {
  font-size: 1.0625rem;
  font-weight: 600;
  margin-bottom: 0.75rem;
  padding-bottom: 0.375rem;
  border-bottom: 0.0625rem solid #eee;
  text-align: center;
}

.profile-form {
  max-width: 26rem;
  margin: 0 auto;
  // text-align: center;
}

/* 收紧每个表单项的底部间距 */
:deep(.el-form-item) {
  margin-bottom: 1rem;
}

/* 标签样式（保持默认左对齐，不强制居中） */
:deep(.el-form-item__label) {
  font-size: 0.8125rem;
  color: #666;
}

/* 输入框默认左对齐 */
:deep(.el-input__inner) {
  text-align: left;
}

/* 单选组保持默认左对齐 */
.profile-form :deep(.el-radio-group) {
  display: inline-flex;
  gap: 0.75rem;
}

.avatar-item {
  display: flex;
  justify-content: center;
}

.avatar-item :deep(.el-form-item__content) {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar-uploader {
  position: relative;
  width: 6.25rem;
  height: 6.25rem;
  border-radius: 50%;
  overflow: hidden;
  cursor: pointer;
  margin: 0 auto;
  border: 0.0625rem solid #eaeaea;
  
  &:hover .upload-overlay {
    opacity: 1;
  }
  
  .avatar-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  
  .upload-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    color: #fff;
    opacity: 0;
    transition: opacity 0.3s;
    
    .el-icon {
      font-size: 1.5rem;
      margin-bottom: 0.375rem;
    }
    
    span {
      font-size: 0.75rem;
    }
  }
}

.readonly-text {
  line-height: 1.75rem;
  color: #333;
}

.balance-wrap {
  display: flex;
  align-items: baseline;
  font-weight: 600;
  color: #ff6a00;

  .currency {
    margin-right: 0.25rem;
    font-size: 1rem;
  }
  .amount {
    font-size: 1rem;
    letter-spacing: 0.02em;
  }
}

/* 操作区居中，减少底部留白 */
.actions :deep(.el-form-item__content) {
  display: flex;
  justify-content: center;
}

.actions {
  margin-bottom: 0;
}

.save-btn {
  padding: 0.375rem 1.25rem;
}

/* 头像弹窗样式，限制预览区域不越界 */
.avatar-dialog {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.avatar-dialog .preview {
  width: 100%;
  max-height: 14rem;
  border: 1px solid #eee;
  border-radius: 0.25rem;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fafafa;
}

.avatar-dialog .preview img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
  display: block;
}

.avatar-dialog .actions-row {
  display: flex;
  gap: 0.5rem;
}

/* 余额操作按钮样式 */
.balance-actions {
  margin-left: 1rem;
  display: flex;
  gap: 0.5rem;
}

/* 充值弹窗样式 */
.recharge-dialog {
  padding: 0.5rem 0;
}

.dialog-actions {
  display: flex;
  justify-content: flex-end;
  gap: 0.5rem;
  margin-top: 1rem;
}

/* 订单列表弹窗样式 */
.order-list-dialog {
  padding: 0.5rem 0;
  // overflow-y: auto;
}

.order-list-header {
  margin-bottom: 1rem;
  display: flex;
  justify-content: flex-end;
}

.order-list-table {
  width: 100%;
  height: calc(90vh - 300px) !important;
}

.amount-text {
  color: #ff6a00;
  font-weight: 600;
}

/* 弹窗固定居中样式 */
:deep(.order-dialog-center) {
  position: fixed !important;
  top: 0 !important;
  left: 0 !important;
  right: 0 !important;
  bottom: 0 !important;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
}

:deep(.order-dialog-center .el-dialog) {
  margin: 0 !important;
  position: fixed !important;
  top: 50% !important;
  left: 50% !important;
  transform: translate(-50%, -50%) !important;
  max-height: 90vh;
  overflow: hidden;
}

:deep(.order-dialog-center .el-dialog__body) {
  max-height: calc(90vh - 120px);
  overflow: hidden;
}

:deep(.order-dialog-center .el-dialog__wrapper) {
  position: fixed !important;
  overflow: hidden !important;
}

:deep(.order-dialog-center .el-overlay) {
  position: fixed !important;
  overflow: hidden !important;
}

/* 表格滚动样式 */
:deep(.order-dialog-center .el-table) {
  height: calc(90vh - 250px) !important;
}

:deep(.order-dialog-center .el-table__body-wrapper) {
  overflow-y: auto !important;
  height: calc(90vh - 300px) !important;
}

:deep(.order-dialog-center .el-table__fixed-right) {
  position: sticky !important;
  right: 0;
  z-index: 10;
}

/* 强制显示滚动条 */
:deep(.order-dialog-center .el-table__body-wrapper::-webkit-scrollbar) {
  width: 8px;
}

:deep(.order-dialog-center .el-table__body-wrapper::-webkit-scrollbar-track) {
  background: #f1f1f1;
  border-radius: 4px;
}

/* 去除表格行阴影，添加边框分隔线 */
:deep(.order-dialog-center .el-table) {
  border: 1px solid #ebeef5;
}

:deep(.order-dialog-center .el-table__row) {
  border-bottom: 1px solid #f0f0f0;
}

:deep(.el-table__row .hover-row) {
  background-color: #f5f7fa !important;
}

:deep(.order-dialog-center .el-table__header) {
  background-color: #fafafa;
  border-bottom: 2px solid #e4e7ed;
}

:deep(.order-dialog-center .el-table__header th) {
  background-color: #fafafa;
  border-bottom: 2px solid #e4e7ed;
  font-weight: 600;
  color: #303133;
}

/* 空数据提示样式 */
:deep(.order-dialog-center .el-table__empty-block) {
  padding: 40px 0;
}

:deep(.order-dialog-center .el-table__empty-text) {
  color: #909399;
  font-size: 14px;
  font-weight: 500;
}
</style>
